Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
How to embed an if statement in a "for of" loop in JS

I have a genuine quetion. Given this simple JS code:

for (let x of array) {
   if (x != array[0]) {
       // do stuff
   }
}

Is there a way to embed the "if" statement directly into the for loop?

I tried something like this:

for (let x of array if x != array[0] {
   // do stuff    
}

And:

for (let x != array[0] of array) {
   // do stuff
}

But both of them didn't work. Let me know if you can find a solution!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can filter the array with the condition and iterate through that result:

const array = [1, 2, 3]

for(let x of array.filter(e => e != array[0])){
    console.log(x)
}

about 4 years ago · Juan Pablo Isaza Report

0

You cant pass a boolean in a "for of" or "for in" loops , the only way of do a comparison for an iteration of a loop is doing :

let array = ["37","728"];

for (let x = 0 ; ((x < array.length) && array[x] == "37") ; x++){
  console.log(array[x]);
}

And it will break the for loop if the second condition pass to true

about 4 years ago · Juan Pablo Isaza Report

0

If you specifically only want to do stuff on the 2nd - nth element, you can just use a for loop and start at 1 instead of 0.

for (let i = 1; i < arr.length; i++) {
  // do stuff
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!